import Utils from '../utils';
import { Storage } from './storage';

interface IStoreModule {
	[key: string]: Storage;
}

/**
 * 模块管理器
 */
const storeModuleManage = (function () {
	class StoreModules {
		// 多久执行一次
		private loopTime: number = 1000 * 1;

		private _timer: any = null;

		private clearCallback: Array<() => void> = [];

		// 所有模块
		modules: IStoreModule = {};

		// 定时清理
		timerClear(timer: number): void {
			clearInterval(this._timer);
			this._timer = setInterval(() => {
				Utils.forEach(this.clearCallback, (fn) => {
					fn && fn();
				});
			}, timer);
		}

		// 开启定时器
		startTimerClear() {
			if (this._timer) return;
			this.timerClear(this.loopTime);
		}

		// 添加清除函数
		appendClear(id: string, fn: () => void): void {
			this.clearCallback.push(fn);
			this.startTimerClear();
		}

		get getIdPrefix() {
			const idList: string[] = [];
			const prefixList: string[] = [];
			Utils.forEach(this.modules, (module, key) => {
				idList.push(String(key));
				prefixList.push(String(module.prefix));
			});
			return {
				id: idList,
				prefix: prefixList,
			};
		}
	}
	const moduleManage = new StoreModules();
	return {
		/**
		 * 获取模块
		 * @param id
		 * @returns
		 */
		get(id: string): Storage {
			return moduleManage.modules[id];
		},

		/**
		 * 设置模块
		 * @param id
		 * @param module
		 */
		set(id: string, module: Storage) {
			moduleManage.modules[id] = module;
			// 过期了自动删除
			if (module.expireAutoDelete) {
				moduleManage.appendClear(module.id, module.autoClear);
			}
			moduleManage.startTimerClear();
		},

		getIdPrefix() {
			return moduleManage.getIdPrefix;
		},

		/**
		 * 获取所有模块
		 * @returns
		 */
		getAll(): IStoreModule {
			return moduleManage.modules;
		},
	};
})();

export { storeModuleManage };
export type { IStoreModule };
